package com.common.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import com.framework.model.impl.DataMap;

public class ExportExcelUtil {

	// 导出Excel
	@SuppressWarnings("deprecation")
	public static boolean exportExcel(HttpServletResponse response, String[] headers, String[] keys,List<DataMap> dataList, String filename) {
		OutputStream os=null;
		WritableWorkbook wbook =null;
		try {
			 os = response.getOutputStream();// 取得输出流
			response.reset();// 清空输出流
			response.setHeader("Content-disposition",
					"attachment; filename="+filename+".xls");// 设定输出文件头
			response.setContentType("application/msexcel");// 定义输出类型

			 wbook = Workbook.createWorkbook(os); // 建立excel文件
			String tmptitle = filename; // 标题
			WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称

			
			  //获取列表遍历数据,生成EXCEL头部
	        if(headers!=null && headers.length>0){
				for (int i=0;i<headers.length;i++)
		        {
					wsheet.addCell(new Label(i, 0, headers[i]));
		        }
			}
	        
	    	if(dataList!=null && dataList.size()>0){
				
				for (int j=0;j<dataList.size();j++) {
					DataMap dataMap1 = dataList.get(j);
					for(String key : keys){
						 wsheet.addCell(new Label(0, j + 1, String.valueOf(dataMap1.get(key))));
					}
			    }
			}
	    	
			// 主体内容生成结束
			wbook.write(); // 写入文件
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}finally{
			if(wbook!=null){
					try {
						wbook.close();
					} catch (WriteException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}
			
			if(os!=null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				} // 关闭流
			}
		}
		return true;
	}
	
	
}
